<?php
/**
 * Date: 2024.8
 * Author: kahn
 */
namespace service\uc;

use cache\MobileLimitCache;
use cache\SmsCodeCache;
use config\Config;
use config\Response;
use models\uc\SmsLogModel;

class SmsService{

    /**
     * 发送验证码
     * @param $mobile
     * @param $ret
     * @return bool
     */
    static function sendCode($mobile, &$ret): bool
    {
        if(!self::checkLimit($mobile, $ret)){
            return false;
        }

        $code = '6666'; //self::_generateCode();
        $reqData = ['code'=>$code];
        $resData = array();

        $smsOk = true; //SmsManager::sendMsg($mobile, $reqData, $resData);
        $sm = SmsLogModel::create([
            'mobile' => $mobile,
            'reqData' => json_encode($reqData, \JSON_UNESCAPED_UNICODE | \JSON_UNESCAPED_SLASHES),
            'resData' => json_encode($resData, \JSON_UNESCAPED_UNICODE | \JSON_UNESCAPED_SLASHES),
            'ip' => getClientIP(),
            'status' => $smsOk ? SmsLogModel::STATUS_SUCCESS : SmsLogModel::STATUS_FAIL,
        ]);

        if($sm->isEmpty()){ //记录log
            \Log::error("sms log error, mobile = $mobile");
            $ret = Response::SYSTEM_ERROR;
            return false;
        }

        if(!$smsOk){
            \Log::error("sms send code error, mobile = $mobile");
            $ret = Response::SMS_FAIL;
            return false;
        }

        //cache
        (new SmsCodeCache())->setCode($mobile,$code);
        self::setLimit($mobile, Config::REGISTER_LOGIN_TYPE_SMS);

        return true;
    }

    /**
     * 验证验证码是否正确
     * @param $mobile
     * @param $clientCode
     * @return bool
     */
    static function verify($mobile, $clientCode): bool
    {
        $vcd = new SmsCodeCache();
        $code = $vcd->getCode($mobile);
        if($code && $code == $clientCode){
            //$vcd->clearCache($mobile);
            return true;
        }
        return false;
    }

    public static function setLimit($mobile, $type){
        $mld = new MobileLimitCache();
        if($type == Config::REGISTER_LOGIN_TYPE_SMS){
            $mld->setMobileLastUseTime($mobile);
        }
        $mld->addMobileDailyUseNum($mobile);
    }

    public static function checkLimit($mobile, &$ret){
        $mld = new MobileLimitCache();
        if($mld->hasMobileLastUseTime($mobile)){
            $ret = Response::MOBILE_LOGIN_FREQUENT;
            return false;
        }
        if($mld->getMobileDailyUseNum($mobile) >= Config::MAX_MSG_NUM){
            $ret = Response::MOBILE_LOGIN_LIMIT;
            return false;
        }
        return true;
    }


}